package la.iok.hzsvn.lewin.movie.cloud.service;

import la.iok.hzsvn.lewin.movie.cloud.entity.WxUserBinding;
import la.iok.hzsvn.lewin.movie.cloud.mapper.WxUserBindingMapper;
import la.iok.hzsvn.lewin.movie.cloud.model.Code2SessionRes;
import la.iok.hzsvn.lewin.mybatis.service.BaseServiceImpl;
import la.iok.hzsvn.share.annotations.NotNull;
import org.springframework.stereotype.Service;

@Service
public class WxUserBindingServiceImpl extends BaseServiceImpl<WxUserBinding, WxUserBindingMapper,Long> implements WxUserBindingService {
    public WxUserBindingServiceImpl(WxUserBindingMapper mapper) {
        super(mapper);
    }

    @Override
    public Long saveOrUpdate(@NotNull Code2SessionRes code2SessionRes, String phoneNumber) {
        WxUserBinding binding = select(code2SessionRes.getUnionID(), code2SessionRes.getOpenID());
        if(binding == null){
            binding = new WxUserBinding();
            binding.setPhoneNumber(phoneNumber);
            binding.setUnionID(code2SessionRes.getUnionID());
            binding.setOpenId(code2SessionRes.getOpenID());
            binding.setSessionKey(code2SessionRes.getSessionKey());
            insertSelective(binding);
        }else{
            binding.setPhoneNumber(phoneNumber);
            binding.setSessionKey(code2SessionRes.getSessionKey());
            updateSessionInfo(binding);
        }
        return binding.getId();
    }

    @Override
    public WxUserBinding select(String unionId, String openId){
        if(unionId == null){
            unionId = "";
        }
        return mapper.select(unionId, openId);
    }

    private void updateSessionInfo(@NotNull WxUserBinding binding){
        mapper.updateSessionInfo(binding);
    }
}
